package objbo.xmlparser.model.finder;

import org.dom4j.Document;
import org.dom4j.Element;

import objbo.xmlparser.model.bean.ElementBean;
import objbo.xmlparser.model.modeler.ElementModeler;
import objbo.xmlparser.model.modeler.XMLFileModeler;

public class ElementFinder
{

	XMLFileModeler	fileModeler	= null;

	public ElementFinder(XMLFileModeler fileModeler)
	{
		this.fileModeler = fileModeler;
	}

	public ElementBean getDocumentData()
	{
		return new ElementModeler().getDocumentElementBean();
	}

	public ElementBean getElementData(ElementBean elementBean)
	{
		ElementModeler modeler = null;
		Document document = null;
		ElementBean bean = null;
		String path = null;
		int index = 0;

		try
		{
			modeler = new ElementModeler();
			document = this.fileModeler.getFileBean().getDocument();

			if (elementBean.getIndex() != -1)
			{
				path = elementBean.getPath();
				index = elementBean.getIndex();
				
				
				
				if (document != null && modeler.loadElementData(document, path, index))
				{

					bean = modeler.getElementBean();
				}
			}
			else
			{
				if (modeler.loadElementData(document.getRootElement(), document))
				{
					bean = modeler.getElementBean();
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return bean;
	}

	public ElementBean getParentElementData(ElementBean elementBean)
	{
		ElementModeler modeler = null;
		Document document = null;
		Element element = null;
		Element parentElement = null;
		ElementBean bean = null;

		String path = null;
		int index = 0;

		try
		{
			path = elementBean.getPath();
			index = elementBean.getIndex();

			modeler = new ElementModeler();

			document = this.fileModeler.getFileBean().getDocument();

			element = (Element) document.selectNodes(path).get(index);
			parentElement = element.getParent();

			if (parentElement != null && modeler.loadElementData(parentElement, document))
			{
				bean = modeler.getElementBean();
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return bean;
	}

}
